#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define ERR_EXIT(m) \
do \
{   \
    perror(m); \
    exit(EXIT_FAILURE); \
}while(0)


//  从管道文件中读数据，写入到目标文件中
int main()
{
    //  1. 以读的方式打开管道文件fifo
    int infd = open("fifo", O_RDONLY, 0644);
    if (infd == -1)
        ERR_EXIT("open falied\n");

    //  2. 以写方式打开目标文件abc.back
    int outfd = open("abc.back", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (outfd == -1)
        ERR_EXIT("open failed\n");

    //  3.从管道文件fifo中读数据并写入到目标文件中
    char buf[1024];
    int n;
    while((n = read(infd, buf, 1024)) > 0)
    {
        write(outfd, buf, n);
    }
    close(infd);
    close(outfd);
    unlink("fifo");

    return 0;
}